<?php


namespace App\Http\Api\Controllers;

use App\Models\CoOrder;
use App\Models\CoUser;

use Illuminate\Support\Facades\DB;
use Yansongda\LaravelPay\Facades\Pay;
use Yansongda\Pay\Log;

class UtilController extends Controller
{
    /**
     * @author anbo
     * @method 微信支付回调接口
     * @descrtption
     */
    public function WxPayNotify()
    {
        $pay = Pay::wechat(config('app.wechat'));
        try {
            $data = $pay->verify(); // 是的，验签就这么简单！
            //触发回调 修改订单状态
            log::info($data);
            if (!is_null($data->get("out_trade_no"))) {
                $out_trade_no = $data->get("out_trade_no");//订单号
                //获取订单信息
                $co_Order = CoOrder::where("order_no", $out_trade_no)->first();
                log::info("订单信息".$co_Order);
                if ($co_Order) {
                    $co_Order->pay_status =1;
                    $co_Order->pay_no = $data->get("transaction_id");//微信支付单号
                    $co_Order->pay_price = $data->get("total_fee"); //微信支付金额
                    $co_Order->pay_time = date('Y-m-d H:i:s',time());
                    $co_Order->safety_code = rand_string(5,0); //生成安全码
                    $co_Order->status = 1;//订单状态:1 待接单
                    /*事务*/
                    DB::beginTransaction();
                    try {
                        $co_Order->save();//保存订单修改
                        log::info("订单：支付完成待接单");
                        DB::commit();
                    } catch (\Exception $e) {
                        DB::rollBack();
                    }
                }
            }
        } catch (\Exception $e) {
            $e->getMessage();
        }
        return $pay->success();// laravel 框架中请直接 `return $pay->success()`
    }
}
